package com.nl.controller.web.controller;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.nl.controller.sms5g.mapper.Sms5gSignatureMapper;
import com.nl.controller.web.mapper.SmsTemplateCheckMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.fastjson.JSONArray;
import com.github.pagehelper.PageInfo;
import com.nl.controller.common.exception.SmsException;
import com.nl.controller.common.model.Response;
import com.nl.controller.common.service.CommonService;
import com.nl.controller.common.util.ResponseUtil;
import com.nl.controller.web.bean.SmsBaseStation;
import com.nl.controller.web.bean.SmsContent;
import com.nl.controller.web.bean.SmsMgrInfo;
import com.nl.controller.web.bean.SmsTemplateAttr;
import com.nl.controller.web.bean.SmsUsers;
import com.nl.controller.web.global.GlobalConst;
import com.nl.controller.web.mapper.SmsBusiMapper;
import com.nl.controller.web.redis.RedisCluster;
import com.nl.controller.web.service.LoginService;
import com.nl.controller.web.service.SmsBaseStationService;
import com.nl.controller.web.service.SmsBusiService;
import com.nl.controller.web.service.SmsContentService;
import com.nl.controller.web.service.SmsTemplateAttrService;
import com.nl.controller.web.service.SmsUserService;
import com.nl.controller.web.util.ExcelUtil;
import com.nl.controller.web.util.FileUtil;

import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;

@RestController
@RequestMapping("/template2")
@Slf4j
public class SmsTemplateAttrController2 {
    @Autowired
    private SmsTemplateAttrService smsTemplateAttrService;
    @Autowired
    private LoginService loginService;
    @Autowired
    private SmsBaseStationService smsBaseStationService;
    @Autowired
    SmsContentService smsContentService;
    @Autowired
    private SmsBusiService smsBusiService;
    @Autowired
    private SmsUserService smsUserService;
    @Autowired
    private CommonService commonService;
    @Autowired
    private SmsBusiMapper smsBusiMapper;
    @Autowired
    private SmsTemplateCheckMapper smsTemplateCheckMapper;

    @Autowired
    private Sms5gSignatureMapper sms5gSignatureMapper;
    
    private SmsTemplateAttr templateAttr;

    @ApiOperation(value = "查询模板信息", notes = "分页查询模板信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page", value = "页码", required = true, dataType = "String"),
            @ApiImplicitParam(name = "limit", value = "每页数量", required = true, dataType = "String"),
            @ApiImplicitParam(name = "cityId", value = "城市编号", required = true, dataType = "String"),
            @ApiImplicitParam(name = "mgrId", value = "项目编号", required = true, dataType = "String"),
            @ApiImplicitParam(name = "state", value = "模板状态", required = true, dataType = "String"),
            @ApiImplicitParam(name = "flag", value = "条件", required = true, dataType = "String")
    })
    @PostMapping("find")
    public Response findTemlpale(
            @RequestParam(value = "page", required = true) int page,
            @RequestParam(value = "limit", required = true) int limit,
            @RequestParam(value = "cityId", required = false) String cityId,
            @RequestParam(value = "mgrId", required = false) String mgrId,
            @RequestParam(value = "mgrName", required = false) String mgrName,
            @RequestParam(value = "state", required = false) String state,
            @RequestParam(value = "flag", required = false) String flag,
            @RequestParam(value = "duty", required = false) String duty,
            @RequestParam(value = "mgrState", required = false) String mgrState,
            @RequestParam(value = "ckeckState", required = false) String ckeckState,
            @RequestParam(value = "openAccount", required = false) String openAccount,
            @RequestParam(value = "countyId", required = false) String countyId,
            @RequestParam(value = "isArrearage", required = false) String isArrearage,
            @RequestParam(value = "sendType", required = false) String sendType,
            @RequestParam Map<String, Object> paramMap
    ) {
        if (!"0".equals(duty)&&("".equals(cityId) || cityId == null)) {
            throw new SmsException("请选择查询条件，开始查询");
        } else {
            PageInfo<SmsTemplateAttr> pageInfo = smsTemplateAttrService.findTempalteAttr(page, limit, cityId, mgrId, mgrName, state, flag,mgrState,ckeckState,openAccount,countyId,isArrearage,sendType);
            log.info(" 查询模板信息：{}", paramMap.toString());
            log.debug("查询模板信息返回参数：{}", pageInfo.getList().toString());
            return ResponseUtil.sucess(pageInfo.getList(), pageInfo.getTotal());
        }
    }


    @ApiOperation(value = "配置模板信息", notes = "配置模板信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "name", value = "项目名称", required = true, dataType = "String"),
            @ApiImplicitParam(name = "cityId", value = "地市编码", required = true, dataType = "String"),
            @ApiImplicitParam(name = "content", value = "短信内容", required = true, dataType = "String"),
            @ApiImplicitParam(name = "startTime", value = "开始时间", required = true, dataType = "String"),
            @ApiImplicitParam(name = "endTime", value = "结束时间", required = true, dataType = "String"),
            @ApiImplicitParam(name = "thresholdStartTime", value = "周期范围开始时间", required = true, dataType = "String"),
            @ApiImplicitParam(name = "thresholdEndTime", value = "周期范围结束时间", required = true, dataType = "String"),
            @ApiImplicitParam(name = "everyDayStartTime", value = "每天开始时间", required = true, dataType = "String"),
            @ApiImplicitParam(name = "everyDayEndTime", value = "每天结束时间", required = true, dataType = "String"),
            @ApiImplicitParam(name = "realTime", value = "延时", required = true, dataType = "String"),
            @ApiImplicitParam(name = "isLocal", value = "本地发送", required = true, dataType = "String"),
            @ApiImplicitParam(name = "cycle", value = "周期", required = true, dataType = "String"),
            @ApiImplicitParam(name = "cycleThreshold", value = "周期数量", required = true, dataType = "String"),
            @ApiImplicitParam(name = "isThreshold", value = "是否设置阀值", required = true, dataType = "String"),
            @ApiImplicitParam(name = "threshold", value = "总阀值数量", required = true, dataType = "String"),
            @ApiImplicitParam(name = "localDate", value = "本地发送保存时间", required = false, dataType = "String"),
            @ApiImplicitParam(name = "isProvince", value = "外地发送范围", required = false, dataType = "String"),
            @ApiImplicitParam(name = "reset", value = "重置阀值", required = false, dataType = "String"),
            
    })
    @PostMapping("configure")
    @Transactional
    public Response insertTemplate(
            @RequestParam("name") String name,
            @RequestParam("cityId") String cityId,
            //@RequestParam("extId") String extId,
            @RequestParam(value = "mgrType", required = false) String mgrType,            
            @RequestParam(value = "content", required = false) String content,
            @RequestParam(value = "startTime", required = false) String startTime,
            @RequestParam(value = "endTime", required = false) String endTime,
            @RequestParam(value = "everyDayStartTime", required = false) String everyDayStartTime,
            @RequestParam(value = "everyDayEndTime", required = false) String everyDayEndTime,
            @RequestParam(value = "realTime", required = false) String realTime,
            @RequestParam(value = "isLocal", required = false) String isLocal,
            @RequestParam(value = "localIsCz", required = false) String localIsCz,
            @RequestParam(value = "nonLocalIsCz", required = false) String nonLocalIsCz,            
            @RequestParam(value = "cycle", required = false) String cycle,
            @RequestParam(value = "cycleThreshold", required = false) int cycleThreshold,
            @RequestParam(value = "thresholdStartTime", required = false) String thresholdStartTime,
            @RequestParam(value = "thresholdEndTime", required = false) String thresholdEndTime,
            @RequestParam(value = "isThreshold", required = false) String isThreshold,
            @RequestParam(value = "threshold", required = false) int threshold,
            @RequestParam(value = "reset", required = false) String reset,
            @RequestParam(value = "localDate", required = false) String localDate,
            @RequestParam(value = "nonlocalDate", required = false) String nonlocalDate,
            @RequestParam(value = "isProvince", required = false) String isProvince,
            @RequestParam(value = "countyId", required = false) String countyId,
            @RequestParam(value = "sendType", required = false) String sendType,
            @RequestParam(value = "flag", required = false) String flag,
            @RequestParam(value = "groupId", required = false) String groupId,
            HttpServletRequest request,
            HttpSession session,
            @RequestParam Map<String, Object> paramMap
    ) {
    	content=content==null?"":content;
        //新增短信项目
        cityId = ("".equals(cityId) ? "25" : cityId);
        String extId=smsUserService.findExtIdByCityId(cityId).get(0);
        extId = ("".equals(extId) ? "" : extId);
      //配置模板信息   
        int result = 0;
        String mgrId="";
        String state = "0";
        state = "4";
        try {
            //先入项目表
        	mgrId = smsBusiService.addBusi(name.trim(), cityId, extId,countyId);
        	//再入模板表
            result = config( mgrId,mgrType,sendType,startTime, endTime, everyDayStartTime, everyDayEndTime, realTime, isLocal,localIsCz,nonLocalIsCz, cycle, cycleThreshold, thresholdStartTime, thresholdEndTime, isThreshold, threshold, reset, localDate, nonlocalDate, isProvince, flag, state,groupId,session, paramMap);
		} catch (Exception e) {
			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
			e.printStackTrace();
		}
        if (result == 1) {
        	return ResponseUtil.sucess(mgrId);
        } else {
            log.debug("配置模板返回参数：{}", result);
            return ResponseUtil.error(result, "配置失败请重试");
        }
    }

    
    @ApiOperation(value = "修改模板信息", notes = "修改模板信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "cityId", value = "地市编码", required = true, dataType = "String"),
            @ApiImplicitParam(name = "mgrId", value = "项目编码", required = true, dataType = "String"),
            @ApiImplicitParam(name = "startTime", value = "开始时间", required = true, dataType = "String"),
            @ApiImplicitParam(name = "endTime", value = "结束时间", required = true, dataType = "String"),
            @ApiImplicitParam(name = "thresholdStartTime", value = "周期范围开始时间", required = true, dataType = "String"),
            @ApiImplicitParam(name = "thresholdEndTime", value = "周期范围结束时间", required = true, dataType = "String"),
            @ApiImplicitParam(name = "everyDayStartTime", value = "每天开始时间", required = true, dataType = "String"),
            @ApiImplicitParam(name = "everyDayEndTime", value = "每天结束时间", required = true, dataType = "String"),
            @ApiImplicitParam(name = "realTime", value = "延时", required = true, dataType = "String"),
            @ApiImplicitParam(name = "isLocal", value = "本地发送", required = true, dataType = "String"),
            @ApiImplicitParam(name = "cycle", value = "周期", required = true, dataType = "String"),
            @ApiImplicitParam(name = "cycleThreshold", value = "周期数量", required = true, dataType = "String"),
            @ApiImplicitParam(name = "isThreshold", value = "是否设置阀值", required = true, dataType = "String"),
            @ApiImplicitParam(name = "threshold", value = "总阀值数量", required = true, dataType = "String"),
            @ApiImplicitParam(name = "localDate", value = "本地发送保存时间", required = false, dataType = "String"),
            @ApiImplicitParam(name = "reset", value = "重置阀值", required = false, dataType = "String"),
            @ApiImplicitParam(name = "newContent", value = "短信内容", required = true, dataType = "String"),
            @ApiImplicitParam(name = "effectTime", value = "生效时间", required = true, dataType = "String"),
            @ApiImplicitParam(name = "isProvince", value = "外地发送范围", required = false, dataType = "String")
    })
    @PostMapping("/modify")
    public Response modifyTemplate(
            @RequestParam(value = "mgrId", required = true) String mgrId,
            @RequestParam(value = "effectTime", required = true) String effectTime,
            @RequestParam(value = "mgrType", required = false) String mgrType,
            @RequestParam(value = "content", required = false) String content,
            @RequestParam(value = "newContent", required = false) String newContent,
            @RequestParam(value = "startTime", required = false) String startTime,
            @RequestParam(value = "endTime", required = false) String endTime,
            @RequestParam(value = "everyDayStartTime", required = false) String everyDayStartTime,
            @RequestParam(value = "everyDayEndTime", required = false) String everyDayEndTime,
            @RequestParam(value = "realTime", required = false) String realTime,
            @RequestParam(value = "isLocal", required = false) String isLocal,
            @RequestParam(value = "localIsCz", required = false) String localIsCz,
            @RequestParam(value = "nonLocalIsCz", required = false) String nonLocalIsCz,
            @RequestParam(value = "cycle", required = false) String cycle,
            @RequestParam(value = "cycleThreshold", required = false) int cycleThreshold,
            @RequestParam(value = "thresholdStartTime", required = false) String thresholdStartTime,
            @RequestParam(value = "thresholdEndTime", required = false) String thresholdEndTime,
            @RequestParam(value = "isThreshold", required = false) String isThreshold,
            @RequestParam(value = "threshold", required = false) int threshold,
            @RequestParam(value = "reset", required = false) String reset,
            @RequestParam(value = "localDate", required = false) String localDate,
            @RequestParam(value = "nonlocalDate", required = false) String nonlocalDate,
            @RequestParam(value = "isProvince", required = false) String isProvince,
            @RequestParam(value = "flag", required = false) String flag,
            @RequestParam(value = "sendType", required = false) String sendType,
            @RequestParam(value = "cityId", required = false) String cityId,
            @RequestParam(value = "groupId", required = false) String groupId,
            HttpSession session,
            @RequestParam Map<String, Object> paramMap
    ) {

        //配置模板信息
        int result = 0;
        result = config( mgrId, mgrType, sendType, startTime, endTime, everyDayStartTime, everyDayEndTime, realTime, isLocal, localIsCz,nonLocalIsCz, cycle, cycleThreshold, thresholdStartTime, thresholdEndTime, isThreshold, threshold, reset, localDate,  nonlocalDate, isProvince, flag, "0",groupId,session, paramMap);
        //欢迎短信添加短信内容并且下行审核短信，5g多媒体短信无短信内容不需要下行
        if (result == 1 ) {
        	//根据传入的是content还是newContent判断对短信内容表做插入或者修改
        	if (null!=content && !"".equals(content)&& "1".equals(sendType)) {
        		result = smsContentService.addContent(mgrId, cityId, content.trim());
        		log.info(" 内容添加参数：{}", paramMap.toString());
 	            log.info(" 内容添加返回数据：{}", result);
 	            if (result == 1) {
	                return ResponseUtil.sucess("添加成功");
	            } else {
	                return ResponseUtil.error(-1, "添加失败请重试");
	            }
			}else if(null!=newContent && !"".equals(newContent)){
				result = smsContentService.modifyContent(mgrId, newContent.trim(), effectTime);
	            log.info(" 内容修改参数：{}", paramMap.toString());
	            log.info(" 内容修改返回数据：{}", result);
	            if (result == 1) {
	                return ResponseUtil.sucess("修改成功");
	            } else {
	                return ResponseUtil.error(-1, "修改失败请重试");
	            }
	            //若为5g多媒体消息则变更项目状态为待审核
			}else if("2".equals(sendType)){
                Map<String, Object> mapState = new HashMap();
                mapState.put("mgrId", mgrId);
                mapState.put("state", "0");
                int modifyResult = smsTemplateCheckMapper.modifyTemplateStatus(mapState);
                if(modifyResult>0){
                    return ResponseUtil.sucess("添加成功");
                }else{
                    return ResponseUtil.error(-1, "操作失败请重试");
                }

            }


        	else {
				return ResponseUtil.sucess("添加成功");
			}
        } else {
            log.debug("配置模板返回参数：{}", result);
            return ResponseUtil.error(result, "配置失败请重试");
        }
    }

    @ApiOperation(value = "查看模板信息", notes = "查看模板信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "mgrId", value = "项目id", required = true, dataType = "String")
    })
    @PostMapping("findTemplate")
    public Response findTemplate(
            @RequestParam(value = "mgrId", required = false) String mgrId,
            @RequestParam(value = "sendType", required = false) String sendType
    ) {
        SmsTemplateAttr smsTemplateAttr;
        smsTemplateAttr = smsTemplateAttrService.findTemplateAttrByMgrId(mgrId);
        //5g项目
        if("2".equals(sendType)){
            String sendNumber = sms5gSignatureMapper.qryChannelNumberByMgrId(mgrId);
            smsTemplateAttr.setSmsChannelNumber(sendNumber);
        }
        SmsContent smsContent = null;
        smsContent=smsContentService.findContentByMgrId(mgrId);
        if (smsContent!=null) {
        	 smsTemplateAttr.setContent(smsContent.getContent());
             smsTemplateAttr.setNewContent(smsContent.getNewContent());
		}
        log.info("短信查询参数：{}", mgrId);
        log.info(" 短信查询参数：{}", smsContent);
        templateAttr = smsTemplateAttr;
        log.info(" 项目信息：{}", smsTemplateAttr.toString());
        return ResponseUtil.sucess(smsTemplateAttr);
    }
    /**
     * 配置模板方法
     * @param mgrId
     * @param startTime
     * @param endTime
     * @param everyDayStartTime
     * @param everyDayEndTime
     * @param realTime
     * @param isLocal
     * @param cycle
     * @param cycleThreshold
     * @param thresholdStartTime
     * @param thresholdEndTime
     * @param isThreshold
     * @param threshold
     * @param reset
     * @param localDate
     * @param flag
     * @param session
     * @param paramMap
     * @return
     */
    private int config(
            String mgrId,
            //String cityId, String extId,
            String mgrType,
             String sendType,
             String startTime,String endTime, String everyDayStartTime,String everyDayEndTime,
            String realTime, String isLocal,String localIsCz,String nonLocalIsCz,String cycle, int cycleThreshold, String thresholdStartTime,
            String thresholdEndTime,String isThreshold,int threshold,String reset,
            String localDate, String nonlocalDate, String isProvince, String flag, String state,String groupId,
            HttpSession session,
            Map<String, Object> paramMap){
    	log.info("开始时间"+startTime+","+endTime+","+thresholdStartTime+","+thresholdEndTime+","+everyDayStartTime);
        log.info(" 配置模板参数：{}", paramMap.toString());
        
        SmsUsers user = (SmsUsers) session.getAttribute("user");

        String operatorId = user.getUserId();
        String operatorPhone = user.getMsisdn();
        //String state = "0";
        if (user.getDuty().equals("0")&&"1".equals(sendType)) {
            state = "2";
        }
        int result = 0;
        //参数处理
        //是否设置阀值, 0不设置  1设置发送总量  2发送周期  3全设置
        if (("0").equals(isThreshold)) {
            cycle = "0";
            threshold = 0;
            cycleThreshold = 0;
        } else if ("1".equals(isThreshold)) {
            cycle = "0";
            cycleThreshold = 0;
        } else if ("2".equals(isThreshold)) {
            threshold = 0;
        }
        if ("".equals(everyDayStartTime) || everyDayStartTime == null) {
            everyDayStartTime = "8:00";
        }
        if ("".equals(everyDayEndTime) || everyDayEndTime == null) {
            everyDayEndTime = "20:00";
        }
        if ("".equals(thresholdStartTime) || thresholdStartTime == null) {
        	thresholdStartTime = null;
        }
        if ("".equals(thresholdEndTime) || thresholdEndTime == null) {
        	thresholdEndTime = null;
        }
        if ("modify".equals(flag)) {
        	SmsTemplateAttr smsTemplateAttr;
            smsTemplateAttr = smsTemplateAttrService.findTemplateAttrByMgrId(mgrId);
            templateAttr = smsTemplateAttr;        	
        }
        result = smsTemplateAttrService.configureTemplate(mgrId,mgrType,sendType,startTime, endTime, thresholdStartTime, thresholdEndTime, everyDayStartTime, everyDayEndTime, realTime, isLocal, localIsCz,nonLocalIsCz, cycle, cycleThreshold, isThreshold, threshold, flag, state,localDate,nonlocalDate,isProvince,reset,operatorPhone,operatorId,groupId);
        log.debug("配置模板返回参数：{}", result);

        //入库成功而且是普通欢迎短信
        if (result == 1) {
        	int sendFlag=0;//如果项目模板没有修改项，则不发送短信
        	StringBuffer sbf = new StringBuffer();
            String content1 = "【欢迎短信】项目:" + smsBusiService.findByMgrId(mgrId).getName() + "已完成配置，请省公司管理员审核;";
            sbf.append(content1);
//            if ("modify".equals(flag)) {
//
//            }
            if (!"0".equals(user.getDuty()) && sendFlag==1) {
            	//非管理员权限入待发表
                String[] msisdn = commonService.templateNotice("1000000001");
                SmsMgrInfo smsMgrInfo = smsBusiMapper.findByMgrId(mgrId);
                Map<String, Object> map = null;
                if (msisdn != null && msisdn.length > 0) {
                    for (String number : msisdn) {
                    	map = new HashMap<String, Object>();
        				map.put("receiver", number);
        				if ("11".equals(smsMgrInfo.getCityId())) {
        					map.put("sender", "106571103");
						}else {
							map.put("sender", "106571102");
						}
        				map.put("result", -1);
        				map.put("cityId", smsMgrInfo.getCityId());
        				map.put("mgrId", mgrId);
        				map.put("mgrName", smsMgrInfo.getName());
        				map.put("cityExtId", smsMgrInfo.getCityExtId());
        				String content = sbf.toString()
        				+"(同意请回复:Y-"+mgrId+"-HY，不同意请回复:Y-"+mgrId+"-HY)";
        				log.info("【短信任务同步接口】插入精准政务待发表,content:"+content);
        				map.put("content", content);
                        log.info("手机号" + number);
                        log.info(sbf.toString());
                    }
                }
            }
            //是否设置阀值, 0 不设置  1设置发送总量 2 发送周期 3 全设
            HashMap<String, Object> map = new HashMap<String, Object>();
            RedisCluster redisCluster=null;
            map.put("mgrId", mgrId);
            map.put("reset", reset);
            if ("1".equals(reset)) {
            	try {
            		
        			redisCluster=new RedisCluster(GlobalConst.REDIS_CONFIG);
        			//String keyName=mgrId+"hy";
        			redisCluster.set(mgrId+"timeCount","0");
        			redisCluster.set(mgrId+"dayCount","0");
        			redisCluster.set(mgrId+"weekCount","0");
        			redisCluster.set(mgrId+"monthCount","0");
        			redisCluster.set(mgrId+"quarterCount","0");
        			redisCluster.set(mgrId+"yearCount","0");
        			redisCluster.set(mgrId+"totalCount","0");
        			log.info("项目id"+mgrId+"重置redis中的阀值成功！");
        			commonService.createSmsOperLog("3", mgrId,"重置阀值", "0", "重置项目"+mgrId+",redis中的阀值");        			
        		} catch (IOException e) {
        			log.info("项目id"+mgrId+"重置redis中的阀值失败！");
        			commonService.createSmsOperLog("3", mgrId,"重置阀值", "1", "重置"+mgrId+",redis中的阀值");
        			e.printStackTrace();
        		}finally {
        			if(null != redisCluster){
        				try {
        					redisCluster.close();
        				} catch (Exception e2) {
        					log.error("close redis exception :"+ e2.toString());
        				}
        			}
        		}
            	
            	
            	
//       	
//            	SingleRedis redis=new SingleRedis();
//            	List<Jedis> jedis=redis.redisCLuster(GlobalConst.REDIS_CONFIG);
//            	jedis.get(0).hset("1", "age", "10");
//            	jedis.get(0).hincrBy("1", "age", 10L);
//            	String r=jedis.get(0).hget("1", "age");
//            	System.out.println(r);
            	
//            	log.info("reset--------------------"+reset);
                smsTemplateAttrService.resetThreshold(map);
            	
			}
            return result;
        } else {
            log.debug("配置模板返回参数：{}", result);
            return  result;
        }
    }
        
    @GetMapping("download")
    public void download(
            HttpSession session,
            HttpServletRequest request, HttpServletResponse response,
            @RequestParam(value = "cityId", required = false) String cityId,
            @RequestParam(value = "mgrId", required = false) String mgrId,
            @RequestParam(value = "mgrName", required = false) String mgrName
    ) {
        
            JSONArray ja = smsBaseStationService.download(cityId,mgrId,mgrName);
            Map<String, String> headMap = new LinkedHashMap<>();
            String title = "";
//            headMap.put("regionId", "区域编码");
            headMap.put("regionName", "区域名称");
            headMap.put("stationId","基站编码");
            headMap.put("stationName", "基站名称");
            title = "项目基站信息";
            ExcelUtil.downloadExcelFile(title, headMap, ja, response,request);
            System.out.println("共" + ja.size() + "条数据,执行");
        
    }
    
    /**
     * desc:复制项目基站
     * @author syl
     * @Date 2019年9月3日 上午10:11:06
     * @param copyMgrId
     * @param mgrId
     */
    @PostMapping("copyStation")
    public Response copyStation(
            @RequestParam(value = "copyMgrId", required = false) String copyMgrId,
            @RequestParam(value = "mgrId", required = false) String mgrId,
            HttpServletRequest request,
            HttpSession session,
            @RequestParam Map<String, Object> paramMap
    ) {
    	int result = 0;
    	List<SmsBaseStation> list = smsBaseStationService.getStation(copyMgrId);
        if(list.size()>0){
        	result = smsBaseStationService.addCopyStation(mgrId,list);
        	if(result>0){
        		commonService.createSmsOperLog("3",mgrId, "修改项目基站信息,项目编码："+mgrId+",复制基站数量："+list.size(), "0","2" );
        	}else {
        		commonService.createSmsOperLog("3",mgrId, "修改项目基站", "1", "2");
			}
        }
        return ResponseUtil.sucess(result);
    }
    
    @ApiOperation(value = "修改模板信息(导入csv文件)", notes = "修改模板信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "cityId", value = "地市编码", required = true, dataType = "String"),
            @ApiImplicitParam(name = "mgrId", value = "项目编码", required = true, dataType = "String"),
            @ApiImplicitParam(name = "startTime", value = "开始时间", required = true, dataType = "String"),
            @ApiImplicitParam(name = "endTime", value = "结束时间", required = true, dataType = "String"),
            @ApiImplicitParam(name = "thresholdStartTime", value = "周期范围开始时间", required = true, dataType = "String"),
            @ApiImplicitParam(name = "thresholdEndTime", value = "周期范围结束时间", required = true, dataType = "String"),
            @ApiImplicitParam(name = "everyDayStartTime", value = "每天开始时间", required = true, dataType = "String"),
            @ApiImplicitParam(name = "everyDayEndTime", value = "每天结束时间", required = true, dataType = "String"),
            @ApiImplicitParam(name = "realTime", value = "延时", required = true, dataType = "String"),
            @ApiImplicitParam(name = "isLocal", value = "本地发送", required = true, dataType = "String"),
            @ApiImplicitParam(name = "cycle", value = "周期", required = true, dataType = "String"),
            @ApiImplicitParam(name = "cycleThreshold", value = "周期数量", required = true, dataType = "String"),
            @ApiImplicitParam(name = "isThreshold", value = "是否设置阀值", required = true, dataType = "String"),
            @ApiImplicitParam(name = "threshold", value = "总阀值数量", required = true, dataType = "String"),
            @ApiImplicitParam(name = "localDate", value = "本地发送保存时间", required = false, dataType = "String"),
            @ApiImplicitParam(name = "reset", value = "重置阀值", required = false, dataType = "String"),
            @ApiImplicitParam(name = "newContent", value = "短信内容", required = true, dataType = "String"),
            @ApiImplicitParam(name = "effectTime", value = "生效时间", required = true, dataType = "String"),
            @ApiImplicitParam(name = "isProvince", value = "外地发送范围", required = false, dataType = "String")
    })
    @PostMapping("/modifyByImport")
    public Response modifyTemplateByImport(
            @RequestParam(value = "mgrId", required = true) String mgrId,
            @RequestParam(value = "mgrType", required = false) String mgrType,
            @RequestParam(value = "effectTime", required = false) String effectTime,
            @RequestParam(value = "newContent", required = false) String newContent,
            @RequestParam(value = "startTime", required = false) String startTime,
            @RequestParam(value = "endTime", required = false) String endTime,
            @RequestParam(value = "everyDayStartTime", required = false) String everyDayStartTime,
            @RequestParam(value = "everyDayEndTime", required = false) String everyDayEndTime,
            @RequestParam(value = "realTime", required = false) String realTime,
            @RequestParam(value = "isLocal", required = false) String isLocal,
            @RequestParam(value = "localIsCz", required = false) String localIsCz,
            @RequestParam(value = "nonLocalIsCz", required = false) String nonLocalIsCz,  
            @RequestParam(value = "cycle", required = false) String cycle,
            @RequestParam(value = "cycleThreshold", required = false) int cycleThreshold,
            @RequestParam(value = "thresholdStartTime", required = false) String thresholdStartTime,
            @RequestParam(value = "thresholdEndTime", required = false) String thresholdEndTime,
            @RequestParam(value = "isThreshold", required = false) String isThreshold,
            @RequestParam(value = "threshold", required = false) int threshold,
            @RequestParam(value = "reset", required = false) String reset,
            @RequestParam(value = "localDate", required = false) String localDate,
            @RequestParam(value = "nonlocalDate", required = false) String nonlocalDate,
            @RequestParam(value = "isProvince", required = false) String isProvince,
            @RequestParam(value = "flag", required = false) String flag,
            @RequestParam(value = "cityId", required = false) String cityId,
            @RequestParam(value = "sendType", required = false) String sendType,
            @RequestParam(value = "importType", required = false) String importType,
            @RequestParam(value = "groupId", required = false) String groupId,
            HttpServletRequest request,
            HttpSession session,
            @RequestParam Map<String, Object> paramMap,
            @RequestParam("file") MultipartFile file
    ) {
       
        //配置模板信息
        int result = 0;
        result = config( mgrId, mgrType,sendType, startTime, endTime, everyDayStartTime, everyDayEndTime, realTime, isLocal, localIsCz,nonLocalIsCz, cycle, cycleThreshold, thresholdStartTime, thresholdEndTime, isThreshold, threshold, reset, localDate, nonlocalDate,isProvince, flag,"0",groupId,session, paramMap);
        if (result == 1) {
            //更改短信内容信息
            if("1".equals(sendType)){
                result = smsContentService.modifyContent(mgrId, newContent.trim(), effectTime);
            }

            log.info(" 内容修改参数：{}", paramMap.toString());
            log.info(" 内容修改返回数据：{}", result);
            if (result == 1) {
            	if (file!=null) {
                	//导入基站信息
                	Map<String, Object> map = new HashMap<>();
                    SmsUsers user = (SmsUsers) request.getSession().getAttribute("user");
                    String now = new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new Date());
                    String fileName = user.getUserId() + now + mgrId;
                    String path = GlobalConst.FILE_STATION_PATH;
                    try {
                        FileUtil.fileUpload(file,request,path,fileName); //文件上传
                        log.info("文件上传成功");
                        log.info(mgrId+"----"+cityId);
                    }catch (Exception e){
                        e.printStackTrace();
                        log.error("文件上传异常");
                        return ResponseUtil.error(1, "文件上传异常");
                    }
                        try {
                            List list = smsBaseStationService.readCsvByImport(path + "/" + fileName, mgrId,cityId,importType); //文件解析
                            return ResponseUtil.sucess(list);
                        } catch (Exception e) {
                            e.printStackTrace();
                            map.put("code", 1);
                            log.error("基站数据错误，请修改");
                            return ResponseUtil.error(1, "基站数据错误，请修改");
                        }               
                } else {
                    return ResponseUtil.error(-1, "添加失败请重试");
                }
            } else {
                return ResponseUtil.error(-1, "修改失败请重试");
            }
        } else {
            log.debug("配置模板返回参数：{}", result);
            return ResponseUtil.error(result, "配置失败请重试");
        }
    }
    
    /**
     * desc:查询项目模板历史表
     * @author syl
     * @Date 2019年10月11日 下午5:29:44
     * @param seqId
     * @param paramMap
     * @return
     */
    @PostMapping("findHis")
    public SmsTemplateAttr findTemplateAttrHis(@RequestParam(value = "seqId", required = true) String seqId,
            @RequestParam Map<String, Object> paramMap){
    	SmsTemplateAttr smsTemplateAttr = smsTemplateAttrService.findTemplateAttrHis(seqId);
    	log.info(" 查询项目模板历史：{}", paramMap.toString());
        log.debug("查询项目模板历史返回参数：{}", smsTemplateAttr.toString());
		return smsTemplateAttr;
    }
    
    @PostMapping("/modifyStation")
    public Response modifyStation(
            @RequestParam(value = "mgrId", required = true) String mgrId,
            @RequestParam(value = "cityId", required = false) String cityId,
            @RequestParam(value = "importType", required = false) String importType,
            HttpServletRequest request,
            HttpSession session,
            @RequestParam Map<String, Object> paramMap,
            @RequestParam("file") MultipartFile file
    ) {
       
            	if (file!=null) {
                	//导入基站信息
                	Map<String, Object> map = new HashMap<>();
                    SmsUsers user = (SmsUsers) request.getSession().getAttribute("user");
                    String now = new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new Date());
                    String fileName = user.getUserId() + now + mgrId;
                    String path = GlobalConst.FILE_STATION_PATH;
                    try {
                        FileUtil.fileUpload(file,request,path,fileName); //文件上传
                        log.info("文件上传成功");
                        log.info(mgrId+"----"+cityId);
                    }catch (Exception e){
                        e.printStackTrace();
                        log.error("文件上传异常");
                        return ResponseUtil.error(1, "文件上传异常");
                    }
                        try {
                            List list = smsBaseStationService.readCsvByImport(path + "/" + fileName, mgrId,cityId,importType); //文件解析
                            return ResponseUtil.sucess(list);
                        } catch (Exception e) {
                            e.printStackTrace();
                            map.put("code", 1);
                            log.error("基站数据错误，请修改");
                            return ResponseUtil.error(1,"基站数据错误，请修改");
                        }               
                } else {
                    return ResponseUtil.error(-1, "添加失败请重试");
                }
    	}
}

